import React, { useEffect, useState } from 'react'
import { Tag } from 'antd';
import Image from '../../components/Image/Image'
import axios from '../../aixos'
import { connect } from 'react-redux'
import Table from '../../components/Table/Table';

function List(props) {
  const [articleList, setArticleList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageIndex, setPageIndex] = useState(1)
  console.log(props)
  const pageSize = 10
  useEffect(() => {
    axios.get('/article', {
      pageIndex,
      pageSize,
      state: 0
    }).then(res => {
      setArticleList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])
  const changePage = (index) => {
    setPageIndex(index)
  }
  const columns = [
    {
      title: '作者',
      dataIndex: 'author',
      render: (obj) => <>{obj.username}</>
    },
    {
      title: '分类',
      dataIndex: 'category',
      render: (obj) => <>{obj.name}</>
    },
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover, recodr) => <Image style={{width: '100px'}} src={cover || recodr.category.icon}/>,
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '简介',
      dataIndex: 'description',
    },
    {
      title: '状态',
      dataIndex: 'state',
      render: (val) => <Tag>{props.articleState[val]}</Tag>
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       <Button type='primary' onClick={() => publish(record._id)}>发布</Button>
    //       <Popconfirm  title={`确认删除这篇文章吗？`}
    //         onConfirm={() => del(record._id)}
    //         okText="Yes"
    //         cancelText="No">
    //         <Button type='danger'>删除</Button>
    //       </Popconfirm>
    //     </Space>
    //   ),
    // },
  ];
  const publish = (record) => {
    const {_id: id} = record
    axios.put('/article', {
      id,
      state: 1
    }).then(() => {
      setArticleList(articleList.filter(item => item._id !== id))
    })
  }
  const del = (id) => {
    console.log(id)
    axios.delete('/article', {
      id
    }).then(() => {
      setArticleList(articleList.filter(item => item._id !== id))
    })

  }
  return (
    <div>
      <Table rowKey='_id' columns={columns} dataSource={articleList} pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }}
      action={{
        edit: {label: '发布', callback: publish},
        delete: {callback: del}
      }}
      />
    </div>
  )
}

export default connect((state) => {
  console.log(state)
  return {
    articleState: state.state.articleState
  }
})(List)
